import config from './config'
const base_url = config.getBaseUrl()

// 处理请求异常状态码
const handleErrorStatus = (err) => {
  let msg = '服务找不到'
  wx.showToast({
    title: `${err}`,
    icon: 'none'
  })
  return msg
}

// 处理请求异常
const handleError = (err) => {
  console.log(err)
  wx.showToast({
    title: err,
    icon: 'error'
  });
}

const request = (url, options) => {
  const contentType = options.method === 'GET' ? 'application/x-www-form-urlencoded' : 'application/json'
  let header = {
    'X-coffee-Token': getApp().globalData.token,
    'content-type': contentType
  }
  return new Promise((resolve, reject) => {
    wx.request({
      // {app.globalData.host}为接口请求中的公共部分写在app.js中
      url: `${base_url}${url}`,
      method: options.method,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data) && options.method === 'POST' ? options.data : options.data,
      header: header,
      success(request) {
        if (request.data.code === 200) {
          resolve(request.data)
        } else {
          handleError(request.data.msg)
          reject(request.data)
        }
      },
      fail(error) {
        reject(error.data)
      }
    })
  })
}

const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options
  })
}
const post = (url, options) => {
  return request(url, {
    method: 'POST',
    data: options
  })
}
const put = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options
  })
}
// 不能声明DELETE（关键字）
const remove = (url, options) => {
  return request(url, {
    method: 'DELETE',
    data: options
  })
}

module.exports = {
  get,
  post,
  put,
  remove
}
